package com.atguigu.tingshu.search.factory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Date: 2025-02-07 星期五 16:38:27
 * Description:
 * 单例饿汉式模式（多线程下是线程安全的）+工厂
 */
public class ScheduleTaskThreadFactory {


    // 1.定义一个定时/延时功能的线程池对象
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    // 2.定义一个实例对象
    private static ScheduleTaskThreadFactory INSTANCE = new ScheduleTaskThreadFactory();

    // 3.私有构造器
    private ScheduleTaskThreadFactory() {

    }

    /**
     * 创建一个对象底层发生三件事
     * 1、为对象分配一块内存空间
     * 2、为对象属性赋值
     * 3、将对象的地址赋值给栈中的引用
     *
     * @return
     */
    public static ScheduleTaskThreadFactory getInstance() {
//        return new ScheduleTaskThreadFactory();
        return INSTANCE;
    }

    /**
     * 定义执行任务的方式：延时任务
     */
    public void execute(Runnable r, Long ttl, TimeUnit timeUnit) {
        scheduledExecutorService.schedule(r, ttl, timeUnit);
    }


    /**
     * 时间差
     *
     * @param currentTime
     * @return
     */
    public long diffTime(Long currentTime) {
        LocalDate localDate = LocalDate.now().plusDays(7);
        LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(2, 0, 0));

        long endTime = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long diffTime = Math.abs(currentTime - endTime);
        return diffTime;
    }

}